﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Text;
using System.EnterpriseServices;
using System.Configuration;
using Models;
using Common;
using Langben.DAL;
using Langben.BLL;
using Langben.App.Models;
using System.Collections;
using System.Data;

namespace Langben.App.Controllers
{
    /// <summary>
    /// 出库详细表
    /// </summary>
    public class ts_billoutdetailController : BaseController
    {

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult Index()
        {
        
            return View();
        }
         /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public ActionResult IndexSef()
        {

            return View();
        }
        /// <summary>
        /// 异步加载数据
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">升序asc（默认）还是降序desc</param>
        /// <param name="search">查询条件</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetData(string id, int page, int rows, string order, string sort, string search)
        {

            int total = 0;
            List<ts_billoutdetail> queryData = m_BLL.GetByParam(id, page, rows, order, sort, search, ref total);
            return Json(new datagrid
            {
                total = total,
                rows = queryData.Select(s => new
                {
                    Id = s.Id
					,c_type = s.c_type
					,i_no = s.i_no
					,i_num = s.i_num
					,c_code = s.c_code
					,f_quant = s.f_quant
					,f_price = s.f_price
					,f_amount = s.f_amount
					,c_comment = s.c_comment
					
                }

                    )
            });
        }

          /// <summary>
        /// 异步加载数据
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">升序asc（默认）还是降序desc</param>
        /// <param name="search">查询条件</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetDataByi_no(string id, string order, string sort, string search, string i_no)
        {

            int total = 0;
            if (search == null)
            {
                search += "i_no&" + i_no + "^";
            }
            List<ts_billoutdetail> queryData = m_BLL.GetByParam(id, 1, 10000, order, sort, search, ref total);

            foreach (var item in queryData)
            {
                item.c_desc = new BLL.ts_goodsBLL().GetAll().Where(o => o.c_code == item.c_code).First().c_desc;
                item.c_model = new BLL.ts_goodsBLL().GetAll().Where(o => o.c_code == item.c_code).First().c_model;
                item.c_unit = new BLL.ts_goodsBLL().GetAll().Where(o => o.c_code == item.c_code).First().c_unit;
            }

            return Json(new datagrid
            {
                total = total,
                rows = queryData.Select(s => new
                {
                    Id = s.Id
                    ,
                    c_type = s.c_type
                    ,
                    i_no = s.i_no
                    ,
                    i_num = s.i_num
                    ,
                    c_code = s.c_code
                    ,
                    f_quant = s.f_quant
                    ,
                    f_price = s.f_price
                    ,
                    f_amount = s.f_amount
                    ,
                    c_comment = s.c_comment
                    ,
                    c_desc = s.c_desc
                    ,
                    c_model = s.c_model
                    ,
                    c_unit = s.c_unit
                }

                    )
            }); 
        }



        #region  数据查询

        /// <summary>
        /// 异步加载数据
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">升序asc（默认）还是降序desc</param>
        /// <param name="search">查询条件</param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public string GetDynamicData(string id, string search)
        {
            string where = string.Empty;

            //if (searchKey != null && searchValue != null && searchKey.ToString() != "" && searchValue.ToString() != "")
            //{
            //    if (where != "")
            //    {
            //        where += " and " + searchKey + "='" + searchValue + "'";
            //    }
            //    else
            //    {
            //        where += " " + searchKey + "='" + searchValue + "'";
            //    }
            //}

            JsonHelper jsh = new JsonHelper();

            string jsonStr = string.Empty;
            jsonStr = GetDyData(where);

            return jsonStr;
        }

        #endregion


        /// <summary>
        /// 返回数据列模板
        /// </summary>
        /// <param name="id"></param>
        [HttpPost]
        [SupportFilter]
        public ActionResult GetColumns(string tabID)
        {
            Hashtable ht = new Hashtable();
            SqlReadXml rx = new SqlReadXml();
            DataSet ds = rx.ReaderDataSet("sel_c_class");

            string jsonStr = "{\"columns\":\"" + CreateDataGridColumnModel(ds.Tables[0]) + "\"}";

            return Json(jsonStr, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        ///  从dataTable创建 jquery easyui datagrid格式的columns参数  
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        protected string CreateDataGridColumnModel(DataTable dt)
        {
            StringBuilder columns = new StringBuilder("[[");
            int width = 0;
            decimal allamount = 0;
            columns.AppendFormat("{{field:'{0}',title:'{1}',align:'center',width:{2},editor:'{3}'}},", "c_id", "领料部门", 120, "text");
            for (int k = 0; k < dt.Rows.Count; k++)
            {
                columns.AppendFormat("{{field:'{0}',title:'{1}',align:'center',width:{2},editor:'{3}'}},", dt.Rows[k]["c_class"], dt.Rows[k]["c_class"], width, "text");
                string a = dt.Rows[k]["c_class"].ToString(); 
            }
            columns.AppendFormat("{{field:'{0}',title:'{1}',align:'center',width:{2},editor:'{3}'}},", allamount, "合计", 80, "text");

            columns.Append("]]");
            return columns.ToString();
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="tabName"></param>
        public string GetDyData(string where)
        {
            Hashtable ht = new Hashtable();
            SqlReadXml rx = new SqlReadXml();

            DataSet dataByName = rx.ReaderDataSet("sel_LLHZB", ht);// new DataSet(); //getData(tabName, type, where);
            JsonHelper jHelp = new JsonHelper();

            int total = dataByName.Tables[0].Rows.Count;
            DataTable dtQueryData = new DataTable();
            if (total > 0)
            {
                dtQueryData = dataByName.Tables[0].AsEnumerable().CopyToDataTable();

            }
            string jsonData = jHelp.DatatableToJson(dtQueryData);

            string jsonStr = "{\"page\":" + 1 + ",\"total\":" + total + ",\"rows\":" + jsonData + "}";
            return jsonStr;
        }



        /// <summary>
        /// 查看详细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [SupportFilter]  
        public ActionResult Details(string id)
        {
            ts_billoutdetail item = m_BLL.GetById(id);
            return View(item);

        }
 
        /// <summary>
        /// 首次创建
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult Create(string id)
        { 
            
            return View();
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult Create(ts_billoutdetail entity)
        {           
            if (entity != null && ModelState.IsValid)
            {
                string currentPerson = GetCurrentPerson();
                //entity.CreateTime = DateTime.Now;
                //entity.CreatePerson = currentPerson;
              
                entity.Id = Result.GetNewId();   
                string returnValue = string.Empty;
                if (m_BLL.Create(ref validationErrors, entity))
                {
                    LogClassModels.WriteServiceLog(Suggestion.InsertSucceed  + "，出库详细表的信息的Id为" + entity.Id,"出库详细表"
                        );//写入日志 
                    return Json(Suggestion.InsertSucceed);
                }
                else
                { 
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.InsertFail + "，出库详细表的信息，" + returnValue,"出库详细表"
                        );//写入日志                      
                    return Json(Suggestion.InsertFail  + returnValue); //提示插入失败
                }
            }

            return Json(Suggestion.InsertFail + "，请核对输入的数据的格式"); //提示输入的数据的格式不对 
        }
        /// <summary>
        /// 首次编辑
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns> 
        [SupportFilter] 
        public ActionResult Edit(string id)
        {
            ts_billoutdetail item = m_BLL.GetById(id);
            return View(item);
        }
        /// <summary>
        /// 提交编辑信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="collection">客户端传回的集合</param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult Edit(string id, ts_billoutdetail entity)
        {
            if (entity != null && ModelState.IsValid)
            {   //数据校验
            
                string currentPerson = GetCurrentPerson();                 
                //entity.UpdateTime = DateTime.Now;
                //entity.UpdatePerson = currentPerson;
                           
                string returnValue = string.Empty;   
                if (m_BLL.Edit(ref validationErrors, entity))
                {
                    LogClassModels.WriteServiceLog(Suggestion.UpdateSucceed + "，出库详细表信息的Id为" + id,"出库详细表"
                        );//写入日志                           
                    return Json(Suggestion.UpdateSucceed); //提示更新成功 
                }
                else
                { 
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.UpdateFail + "，出库详细表信息的Id为" + id + "," + returnValue, "出库详细表"
                        );//写入日志                           
                    return Json(Suggestion.UpdateFail  + returnValue); //提示更新失败
                }
            }
            return Json(Suggestion.UpdateFail + "请核对输入的数据的格式"); //提示输入的数据的格式不对               
          
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>   
        [HttpPost]
        public ActionResult Delete(FormCollection collection)
        {
            string returnValue = string.Empty;
            string[] deleteId = collection["query"].GetString().Split(',');
            if (deleteId != null && deleteId.Length > 0)
            { 
                if (m_BLL.DeleteCollection(ref validationErrors, deleteId))
                {
                    LogClassModels.WriteServiceLog(Suggestion.DeleteSucceed + "，信息的Id为" + string.Join(",", deleteId), "消息"
                        );//删除成功，写入日志
                    return Json("OK");
                }
                else
                {
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.DeleteFail + "，信息的Id为" + string.Join(",", deleteId)+ "," + returnValue, "消息"
                        );//删除失败，写入日志
                }
            }
            return Json(returnValue);
        }
     
        IBLL.Its_billoutdetailBLL m_BLL;

        ValidationErrors validationErrors = new ValidationErrors();

        public ts_billoutdetailController()
            : this(new ts_billoutdetailBLL()) { }

        public ts_billoutdetailController(ts_billoutdetailBLL bll)
        {
            m_BLL = bll;
        }
        
    }
}


